﻿using BL_Client.ServiceReference1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UI
{
    public partial class Users : System.Web.UI.Page
    {
        static BL_Client.IBL bl;
        static User user;

        public Users()
        {
            bl = new BL_Client.BL();
            user = bl.GetUserByEmail(User.Identity.Name);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!userIsAdmin(user))
            {
                jTableScript.InnerHtml = @"<h1>You are not authorized to visit this page</h1>";
            }
            else
                jTableScript.InnerHtml = @"<script type=""text/javascript"">
                                            $(document).ready(function () {
                                                $('#UsersTableContainer').jtable({
                                                    title: 'Table of Users',
                                                    actions: {
                                                        listAction: '/Users.aspx/UsersList',
                                                        createAction: '/Users.aspx/CreateUser',
                                                        updateAction: '/Users.aspx/UpdateUser',
                                                        deleteAction: '/Users.aspx/DeleteUser'
                                                    },
                                                    fields: {
                                                        ID: {
                                                            key: true,
                                                            list: false
                                                        },
                                                        FirstName: {
                                                            title: 'First Name',
                                                            width: '20%'
                                                        },
                                                        LastName: {
                                                            title: 'Last Name',
                                                            width: '20%'
                                                        },
                                                        Email: {
                                                            title: 'Email',
                                                            width: '30%'
                                                        },
                                                        Password: {
                                                            title: 'Password',
                                                            type: 'password',
                                                            width: '20%',
                                                        },
                                                        Role: {
                                                            title: 'Role',
                                                            width: '20%',
                                                            options: { '0': 'Admin', '1': 'AvBait' }
                                                        }
                                                    },
                                                    formCreated: function (event, data) {
                                                                    data.form.find('input[name=""FirstName""]').addClass('validate[required]');
                                                                    data.form.find('input[name=""LastName""]').addClass('validate[required]');
                                                                    data.form.find('input[name=""Email""]').addClass('validate[required,custom[email]');
                                                                    data.form.find('input[name=""Password""]').addClass('validate[required]');
                                                                    data.form.validationEngine();
                                                    },
                                                    formSubmitting: function (event, data) {
                                                        return data.form.validationEngine('validate');
                                                    },
                                                    formClosed: function (event, data) {
                                                        data.form.validationEngine('hide');
                                                        data.form.validationEngine('detach');
                                                    }
                                                });

                                                $('#UsersTableContainer').jtable('load');
                                            });
                                        </script>";
            
        }

        [WebMethod(EnableSession = true)]
        public static object UsersList()
        {
            try
            {
                //Get data from database
                List<User> users = bl.GetAllUsers().ToList();

                //Return result to jTable
                return new { Result = "OK", Records = users, TotalRecordCount = users.Count };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object CreateUser(User record)
        {
            if (!userIsAdmin(user))
                return new { Result = "ERROR" };

            try
            {
                if (bl.AddUser(record))
                {
                    User addedUser = record;
                    return new { Result = "OK", Record = addedUser };
                }
                else
                {
                    return new { Result = "ERROR", Message = "User insertion error" };
                }
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object UpdateUser(User record)
        {
            if (!userIsAdmin(user))
                return new { Result = "ERROR" };

            try
            {
                bl.UpdateUser(record);
                return new { Result = "OK" };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object DeleteUser(int ID)
        {
            if (!userIsAdmin(user))
                return new { Result = "ERROR" };

            try
            {
                bl.RemoveUser(ID);
                return new { Result = "OK" };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        private static bool userIsAdmin(User user)
        {
            return (user.Role == Role.Admin);
        }
    }
}